# auth.py
from flask import Blueprint, jsonify, request, make_response
from flask_jwt_extended import create_access_token, set_access_cookies, unset_jwt_cookies
import flaskapp.services.user as userService
import logging

logger = logging.getLogger(__name__)
token_bp = Blueprint('token', __name__)


@token_bp.route('/api/token', methods=['POST'])
def create():
    try:

        username = request.form.get("username", None)
        password = request.form.get("password", None)

        userInfo = userService.findOne(username)
        print(userInfo)
        if userInfo is None:
            return jsonify({"code": -1, "message": "Bad username or password 1"}), 401
        else:
            if userInfo["password"] != password:
                return jsonify({"code": -1, "message": "Bad username or password 2"}), 401
            else:
                logger.info(f"find user {username}")

        access_token = create_access_token(
            identity={"username": username, "id": str(userInfo["_id"])})
        # response= jsonify(
        #     {"code": 0, "message": "success", "token": access_token})

        response = make_response(
            {"code": 0, "message": "success", "token": access_token})
        response.set_cookie("token", access_token, httponly=True, max_age=3600)
        set_access_cookies(response, access_token)
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})


@token_bp.route('/api/token', methods=['DELETE'])
def logout():
    try:
        response = jsonify({"code": 0})
        unset_jwt_cookies(response)
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})
